package com.springcloud.demo.test.shell.sshj;

import net.schmizz.keepalive.KeepAliveProvider;
import net.schmizz.sshj.DefaultConfig;
import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.common.IOUtils;
import net.schmizz.sshj.connection.channel.direct.Session;
import net.schmizz.sshj.transport.verification.PromiscuousVerifier;

import java.io.IOException;

/**
 * @author zhouyang
 * @Description
 * @date 2018/10/15
 */
public class SSHClientGroup {

    SSHHost[] hosts;
    SSHClient[] sshClients;

    public SSHClientGroup(SSHHost... hosts) {
        this.hosts = hosts;
        init();

    }

    private void init() {
        sshClients = new SSHClient[hosts.length];
        int i = 0;
        for (SSHHost host : hosts) {
            try {
                DefaultConfig defaultConfig = new DefaultConfig();
                defaultConfig.setKeepAliveProvider(KeepAliveProvider.KEEP_ALIVE);
                SSHClient ssh = new SSHClient(defaultConfig);
                sshClients[i++] = ssh;

                ssh.addHostKeyVerifier(new PromiscuousVerifier());
                ssh.connect(host.host);
                ssh.getConnection().getKeepAlive().setKeepAliveInterval(5); // every 60sec
                ssh.authPassword(host.user, host.passwd);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public SSHClientGroup exec(String command) {
        for (SSHClient ssh : sshClients) {

            try {
                Session session = ssh.startSession();
                Session.Command cmd = session.exec(command);
                System.out.println("host " + ssh.getRemoteHostname() + " out put:\n"
                        + IOUtils.readFully(cmd.getInputStream()).toString());
                session.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        return this;
    }

    public void close() throws IOException {
        for (SSHClient ssh : sshClients) {
            ssh.close();
        }
    }

}
